$(document).ready(function(){
	setDialog();
	closeDialog();
	//初始化表格
	$('#dataGridTable').datagrid({
            title:"用户管理",
    		method:"get",
    		dataType: 'json',
    		pageSize:20,
    		pageList:[10,20,30,40],
    		frozenColumns:
				[[
		      	  	{field:'ck',checkbox:'true'}
		        ]],
    		columns:[[ 
    		            {field:'userName',title:'用户名',width:120,align:'center'}, 
    		            {field:'realName',title:'真实姓名',width:80,align:'center'},
//	    		           {field:'systemName',title:'系统名称',width:100,align:'center'},
//	    		           {field:'systemCode',title:'系统编码',width:100,align:'center'},
    		            {field:'userState',title:'员工状态',width:70,align:'center',formatter:formatUserState},
    		            {field:'userType',title:'用户类型',width:70,align:'center',formatter:formatUserType},
    		            {field:'userMobile',title:'手机号码',width:100,align:'center'},
    		            {field:'userEmail',title:'电子邮箱',width:170,align:'center'},
    		            {field:'lastModifiedUser',title:'记录最后修改者',width:lastModifiedWidth,align:'center'},
    		            {field:'lastModifiedTime',title:'记录最后修改时间',width:createTimeWidth,align:'center'}
    		         ]]
	  });	
//	$('#realName').textbox('textbox').keydown(function (e) {
//	   if (e.keyCode == 13) {
//		   $('#realName').textbox('setValue', $(this).val());
//		   query();
//	    }
//	});
//	$('#dataInfoDialog_sysNameFilt').combobox({
//	    onSelect : function(rec){
//	    	query();
//	    }
//	 });
	$('#searchRoleIds').combogrid({    
	    panelWidth:560,
	    panelHeight:500,
	    rownumbers:true,
	    pagination:true,
	    fitColumns:true,
	    multiple:true,
	    pageSize:200,
  		editable:false,
  		toolbar:'#role_search_comboGrid_tools',
  		url:'./role/findUamsRoles.do',
	    idField:'roleId',    
	    textField:'roleName',    
	    columns:[[    
            	{field:'roleId',title:'角色名称',width:150,hidden:'true',align:'center'},  
            	{field:'roleName',title:'角色名称',width:150,align:'center'},
            	{field:'systemName',title:'系统名称',width:150,align:'center'}, 
                {field:'lastModifiedUser',title:'记录最后修改者',width:lastModifiedWidth,align:'center'},
	            {field:'lastModifiedTime',title:'记录最后修改时间',width:createTimeWidth,align:'center'}
                ]]
	});
	$('#userRolesIds').combogrid({    
	    panelWidth:560,
	    panelHeight:500,
	    rownumbers:true,
	    pagination:true,
	    fitColumns:true,
	    multiple:true,
	    pageSize:200,
  		editable:false,
  		toolbar:'#role_comboGrid_tools',
  		url:'./role/findUamsRoles.do',
	    idField:'roleId',    
	    textField:'roleName',    
	    columns:[[    
            	{field:'roleId',title:'角色名称',width:150,hidden:'true',align:'center'},  
            	{field:'roleName',title:'角色名称',width:150,align:'center'},
            	{field:'systemName',title:'系统名称',width:150,align:'center'}, 
                {field:'lastModifiedUser',title:'记录最后修改者',width:lastModifiedWidth,align:'center'},
	            {field:'lastModifiedTime',title:'记录最后修改时间',width:createTimeWidth,align:'center'}
                ]]
	});
});

//弹出修改密码窗口
function openUpdatePawDiglog(){
    if($('#dataGridTable').datagrid('getSelected')){
		$("#paswUpdateDiv").dialog({
			title:"密码重置",
			modal: true,         	//模式窗口：窗口背景不可操作
			collapsible : false,  	//可折叠，点击窗口右上角折叠图标将内容折叠起来
			resizable : false,    	//可拖动边框大小
			closed:true,
			onClose: function () { 
			  $('#paswUpdateForm').form('clear');
			},
			buttons: [{
	            text: '确定',
	            iconCls: 'icon-ok',
	            handler: updateUserPsw
	        }, {
	            text: '取消',
	            iconCls: 'icon-cancel',
	            handler: function () {
	                $('#paswUpdateDiv').dialog('close');                   
	            }
	        }]
		}); 	
		
		var selectedRow = $('#dataGridTable').datagrid('getSelections');
		$("#paswUpdateId").val(selectedRow[0].userId);
		$("#paswUpdateName").textbox('setValue',selectedRow[0].userName);
		$("#paswUpdateRealName").textbox('setValue',selectedRow[0].realName);
		$("#paswNewPassword").textbox('setValue','');
		$("#paswfirmPassword").textbox('setValue','');
		$("#paswUpdateDiv").dialog('open');
    }else{
    	noSelectData();
    }
}

//修改密码的保存按钮
function updateUserPsw() {
    $('#paswUpdateForm').form('submit',{
		url:'./user/updateUamsUserPsw.do',
		onSubmit:function(){
			//判断密码是否确认正确
			var flag = true;
			var pass = $("#paswNewPassword").textbox('getValue');
			var passCif = $("#paswfirmPassword").textbox('getValue');
			if(passCif != pass){
				flag = false;
				$.messager.alert('提示', '两次输入密码不一样！', 'info');
			}
			return $(this).form('validate')&&flag;
		},
		success:function(data){
			if(data = "success"){
				$('#paswUpdateDiv').dialog('close');
			    $.messager.alert('提示', '修改密码成功!', 'info');
			    $("#dataGridTable").datagrid('reload');
			}else {
				 $.messager.alert('提示', data.msg, 'info');
			}
		}
	});
}

//删除数据
function delUser(){
	if($('#dataGridTable').datagrid('getSelected')){
		var ids = [];
		var cods = [];
		var selectedRow = $('#dataGridTable').datagrid('getSelections');
		for(var i=0;i<selectedRow.length;i++){
			ids.push(selectedRow[i].userId);
			cods.push(selectedRow[i].userName);
		}
		var userId = ids.join(',');
		$.messager.confirm('删除提示', '   删除该用户后，它对应的角色，菜单资源，数据关系都将删除，你确定删除下列数据吗?<br/><center>'
				+cods.join(',')+'</center>', function(r){
				if (r){
					var url = './user/deleteUamsUserByUserId.do?userId='+userId;
					$.ajax({
						async : false,
						cache:false,
						type: 'post',
						dataType : "json",
						url:url,
						error: function (msg) {
							console.dir(msg);
							sysErrorShow('请求失败!');
						},success:function(data){
							if(data.code == 200){
								sysMsgShow("删除成功!");
								query();
								closeDialog();
							}else{
								messgage = data.msg;
							}
							sysMsgShow(messgage);
							reloadTable();
						}
					});
				}
		});
	}
	else
	{
		noSelectData();
	}
}

//查询数据
function query(){
	var userName = $("#search_userName").textbox("getValue");
	var realName = $("#search_realName").textbox("getValue");
	var userType = $("#search_userType").combobox("getValue");
	var roleId = $("#searchRoleIds").combogrid("getValue");
	var queryParams = {userName:userName,realName:realName,userType:userType,roleId:roleId
			};
	$('#dataGridTable').datagrid('load',queryParams);
	$("#dataGridTable").datagrid("unselectAll");
}

//==============================条件栏：选择角色条件=======================
//查询用户角色 检索的用户
function querySearchSysRole(){
	$("#searchRoleIds").combogrid("grid").datagrid("reload", {
		'systemCode' : $("#role_search_systemCode").combobox("getValue"),
		'roleName' : $("#search_roleName").val()
	});
}
//刷新
function refleshSearchSysRole(rolesIdArray){
	$("#role_search_systemCode").combobox("setValue",'');//
	$("#search_roleName").textbox("setValue",'');//
	$("#searchRoleIds").combogrid("grid").datagrid("reload", {
		'systemCode' : '',
		'roleName' : ''
	});
}
//===========================编辑：查询角色===============================
//查询用户角色
function querySysRole(){
	var cobo = $("#userRolesIds");
	$("#userRolesIds").combogrid("grid").datagrid("reload", {
		'systemCode' : $("#search_systemCode").combobox("getValue"),
		'roleName' : $("#roleName").val(),
//		'rolesIds' : $('#roleIds').combogrid('getValues').join('#')
	});
}

function refleshSysRole(rolesIdArray){
	$("#search_systemCode").combobox("setValue",'');//
	$("#rolesName").textbox("setValue",'');//
	$("#userRolesIds").combogrid("grid").datagrid("reload", {
		'systemCode' : '',
		'rolesIds' : '',
		'rolesName' : ''
	});
}
/**--------------操作弹出框------------------**/
//初始化模窗
function setDialog(){
	$('#userInfoDialog').dialog({
		modal: true,
		collapsible : true,
		resizable : true,
		onClose : function(){
			resetDialog();
		}
	});
}

//打开添加模窗
function openDialog_add(){ 
	$('#userInfoDialog').dialog({
		closed: false,
		modal:true,
        title: "新增用户",
        buttons: [{
            text: '确定',
            iconCls: 'icon-ok',
            handler: saveUamsUser
        }, {
            text: '取消',
            iconCls: 'icon-cancel',
            handler: function () {
                $('#userInfoDialog').dialog('close');                    
            }
        }]
    });
}

//保存信息
function saveUamsUser(){
	var userId=$("#userInfoDialog_userId").val();
	var userName=$("#userInfoDialog_userName").val();
	var realName=$("#userInfoDialog_realName").val();
	var userSex=$("#userInfoDialog_userSex").combobox('getValue');
	var userState=$("#userInfoDialog_userState").combobox('getValue');
	var userType=$("#userInfoDialog_userType").combobox('getValue');
	var userMobile=$("#userInfoDialog_userMobile").val();
	var userEmail=$("#userInfoDialog_userEmail").val();
	var userQQ=$("#userInfoDialog_userQQ").val();
	var userAddr=$("#userInfoDialog_userAddr").val();
//	var systemCode=$("#userInfoDialog_sysName").combobox('getValue');
	if(userName==null||userName==''){
		sysMsgShow("用户名称不允许为空!");
		return false;
	}else if(realName==null||realName==''){
		sysMsgShow("真实姓名不允许为空!");
		return false;
	}else if(userSex==null||userSex==''){
		sysMsgShow("性别不允许为空!");
		return false;
	}else if(userType==null||userType==''){
		sysMsgShow("类型不允许为空!");
		return false;
	}else if(userMobile==null||userMobile==''){
		sysMsgShow("手机号码不允许为空!");
		return false;
	}else if(!isMobileNum(userMobile)){
		sysMsgShow("手机号码不正确!");
		return false;
	}else if(userEmail==null||userEmail==''){
		sysMsgShow("邮箱不允许为空!");
		return false;
	}else if(!isEmail(userEmail)){
		sysMsgShow("邮箱不正确!");
		return false;
	}else{
		$.ajax({
			async : false,
			cache:false,
			type: 'post',
			dataType : "json",
			data : {
				"userId" : userId,
//				"systemCode" : systemCode,
				"userName" : userName,
				"realName" : realName,
				"userSex" : userSex,
				"userType" : userType,
				"userMobile" : userMobile,
				"userEmail" : userEmail,
				"userQQ" : userQQ,
				"userAddr" : userAddr,
				"userState" : userState
			},
			url: './user/createUamsUser.do',//请求的action路径
			error: function () {
				sysErrorShow('请求失败!');
			},success:function(data){
				var messgage = userId?"修改成功!":"添加成功!";
				if(data.code == 200){
					query();
					closeDialog();
				}else{
					messgage = data.msg;
				}
				sysMsgShow(messgage);
			}
		});
	
	}	
}

//编辑信息
function openDialog_edit(){
	if($('#dataGridTable').datagrid('getSelected')){
		var userId = $('#dataGridTable').datagrid('getSelections')[0].userId;
		var row = $('#dataGridTable').datagrid('getSelections')[0];
		var userId = $("#userInfoDialog_userId").val(userId);
		var userName = $("#userInfoDialog_userName").textbox('setValue',row.userName);
		var realName = $("#userInfoDialog_realName").textbox('setValue',row.realName);
		var userType = $("#userInfoDialog_userType").combobox('setValue',row.userType);
		var userSex=  $("#userInfoDialog_userSex").combobox('setValue',row.userSex);
		var userStatus=$("#userInfoDialog_userStatus").combobox('setValue',row.userStatus);
		var userMobile =$("#userInfoDialog_userMobile").textbox('setValue',row.userMobile);
		var userEmail =$("#userInfoDialog_userEmail").textbox('setValue',row.userEmail);
		var userQQ =$("#userInfoDialog_userQQ").textbox('setValue',row.userQQ);
		var userAddr =$("#userInfoDialog_userAddr").textbox('setValue',row.userAddr);
		var userState =$("#userState_out").combobox('setValue',row.userState);//更改
		$('#userInfoDialog').dialog('setTitle','编辑用户'); 
		openDialog_add();
	}
	else
	{
		noSelectData();
	}
}

	


/**--------------操作弹出框------------------**/
//关闭模窗
function closeDialog(){
	$('#userInfoDialog').dialog('close');
}

//清空控件值
function resetDialog(){
	$("#userInfoDialog_userId").val('');
	$("#userInfoDialog_userName").textbox('setValue','');
	$("#userInfoDialog_realName").textbox('setValue','');
	$("#userInfoDialog_userSex").combobox('setValue','0');
	$("#userInfoDialog_userType").textbox('setValue','');
	$("#userInfoDialog_userEmail").textbox('setValue','');
	$("#userInfoDialog_userQQ").textbox('setValue','');
	$("#userInfoDialog_userAddr").textbox('setValue','');
	$("#userInfoDialog_userState").combobox('setValue','1');
	$("#userInfoDialog_userMobile").textbox('setValue','');
//	$("#userInfoDialog_systemCode").combobox('setValue','');
//	$('#OutUserPassword').textbox('setValue','');
//	$('#OutUserPasswordQR').textbox('setValue','');
}

//清空更改密码控件值
function resetUpdatePaswordDialog(){
	$("#paswUpdateId").val('');
	$("#paswUpdateName").textbox('setValue','');
	$("#paswUpdateRealName").textbox('setValue','');
	$("#paswNewPassword").textbox('setValue','');
	$("#paswfirmPassword").textbox('setValue','');
}

//刷新表格
function reloadTable(){
	$('#dataGridTable').datagrid('reload');
}

//刷新
function refresh(){
	$("#search_userName").textbox('setValue','');
	$("#search_realName").textbox('setValue','');
	$("#search_userType").combobox('setValue','');
	$("#searchRoleIds").combogrid('setValue','');
//	$("#search_systemCode2").combobox('setValue','');
//	$("#userInfoDialog_sysNameFilt").combobox('setValue','');
	query();
}

//加载用户角色
function loadUserRoles_out(depId,roleId){
	var dId = $('#userRolesIds_out').val();
	if('0' == dId){
		//window.bgidx = {treeNotLeafSelected:true};
		$('#roleIds_out').combogrid({    
    	    panelWidth:560,
    	    panelHeight:250,
    	    rownumbers:true,
    	    pagination:true,
    	    fitColumns:true,
    	    pageSize:500,
      		editable:false,
      		toolbar:'#role_comboGrid_tools_out',
      		multiple:true,
      		url:'sys/findRole.action',
    	    idField:'rolesId',    
    	    textField:'rolesName',    
    	    columns:[[    
                	{field:'rolesId',title:'角色名称',width:150,hidden:'true',align:'center'},  
                	{field:'systemName',title:'系统名称',width:150,align:'center'}, 
                    {field:'roleName',title:'角色名称',width:150,align:'center'},
                    {field:'createUser',title:'记录建立者',width:createUserWidth,align:'center'},
                    {field:'createTime',title:'记录建立时间',width:createTimeWidth,align:'center'}   
                    ]],
                    onLoadSuccess:function(){
                    	$('#userRolesIds_out').val("1");
                    	if($('#roleIds_out').combogrid('getValues').length>0){
                    		
                    	}else{
                    		if(roleId != undefined){
                    			$('#roleIds_out').combogrid('setValues',roleId);
                    		}
                    	}
                    }
    		});
	}else{
		if(roleId != undefined){
		$('#roleIds_out').combogrid('setValues',roleId);
		} else {
			return;
		}
	}


}

function formatUserType(value,row){
	var userType = row.userType;
	if(userType){
		switch (userType) {
		case '0': return 'UAMS管理员';
		case '1': return '华大员工';
		case '2': return '外包同事';
		case '3': return '外部用户';
		}
	}
	return '';
}

function formatUserState(value,row){
	var userState = row.userState;
	return (userState=='0'?'离职':(userState=='1'?'在职':''));
}

//判断手机
function isMobileNum(str) {
	var re = /^(((13[0-9]{1})|(17[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
	if(re.test(str)){
		return re.test(str);
	} else {
		re = /^(010|021|022|023|024|025|026|027|028|029|852)\d{8}$/;
		return re.test(str);
	}
}
//判断邮箱
function isEmail(str) {
	var re = /^([a-zA-Z0-9]+[-|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
	return re.test(str);
}